package com.weixin.demo.kotlinboot.util

import com.google.gson.Gson
import com.qiniu.common.QiniuException
import com.qiniu.common.Zone
import com.qiniu.storage.Configuration
import com.qiniu.storage.UploadManager
import com.qiniu.storage.model.DefaultPutRet
import com.qiniu.util.Auth

/**
 *
 * @author zhenggm
 * @version 1.0.0
 */

class UploadImage {
    // 七牛云的sdk key
    private val accessKey = "l1ortG5fYrSMlTeAsiLCpAP08tleIo6jZZy_Tjg3"
    private val secretKey = "vFDYe4rpysp_hgScRGjFf8_enWJgli2_Wt0IWY7P"
    // 指定私密空间名称
    private val bucket = "luway"

    fun upload(path: String, filename: String) {
        init(path, filename)
    }

    private fun init(path: String, filename: String) {
        //构造一个带指定Zone对象的配置类
        val cfg = Configuration(Zone.zone0())
        //...其他参数参考类注释
        val uploadManager = UploadManager(cfg)
        //...生成上传凭证，然后准备上传
        //如果是Windows情况下，格式是 D:\\qiniu\\test.png
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        val auth = Auth.create(accessKey, secretKey)
        val upToken = auth.uploadToken(bucket)
        try {
            val response = uploadManager.put(path, filename, upToken)
            //解析上传成功的结果
            val putRet = Gson().fromJson(response.bodyString(), DefaultPutRet::class.java)
            System.out.println(putRet.key)
            System.out.println(putRet.hash)
        } catch (ex: QiniuException) {
            val r = ex.response
            System.err.println(r.toString())
            try {
                System.err.println(r.bodyString())
            } catch (ex2: QiniuException) {
                //ignore
            }

        }

    }
}